/**
 * Created by oneminute on 7/17/14.
 */

var lz = require("../lib/utils/modules")();

exports.post = function (_req, _res, _opts, _callback) {
    var user = _req.user;
    if (!user) {
        lz.Logger.warn("/updategoods: 未上传有效uid");
        _callback(lz.Config.errors.getError(lz.Config.errors.REQUEST_TEMPUSER_ERROR));
        return;
    }
    var photos = [];
    for (var i = 1; i <= 4; i++) {
        if (_req.files["photo" + i] && _req.files["photo" + i].size > 0) {
            photos.push(_req.files["photo" + i].path);
            lz.Logger.debug("path: ", _req.files["photo" + i].path);
        }
    }
    var gid = _opts.gid;
    var description = _opts.description;
    var price = _opts.price;

    var commodity = new lz.Commodity({id: gid});
    commodity.load({method: "byId"}, function (_err, _commodity) {
        if (!_commodity) {
            lz.Logger.warn('/updategoods: 没有找到商品。');
            _callback(lz.Config.errors.getError(lz.Config.errors.REQUEST_NO_COMMODITY));
            return;
        }
        if (commodity.uid !== user.id) {
            lz.Logger.warn('/updategoods: 用户上传的商品不属于当前用户。');
            _callback(lz.Config.errors.getError(lz.Config.errors.REQUEST_DATA_NOT_BELANG_USER));
            return;
        }
        lz.ImageManager.handleGoodsPhotos(photos, function (err, _photonames) {
            commodity.photos = _photonames;
            commodity.description = description;
            commodity.price = price;
            commodity.save(function (_err, _commodity) {
                if (_commodity) {
                    lz.Logger.debug("更新商品成功。");
                    _callback(null, user);
                } else {
                    lz.Logger.warn("更新商品失败。");
                    _callback(_err, user);
                }
            });
        });
    });
};